package com.haiermzj.server;

import android.content.Context;
import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by wanghaixin on 17/8/4.
 */
public class MyServerSocket {
    private final ServerSocket serverSocket;
    private int port = 11223;
    private String x;
    private MainActivity activity;


    public MyServerSocket() throws Exception {

        serverSocket = new ServerSocket(port, 3);
        System.out.println("服务器启动!" + InetAddress.getLocalHost());

    }

    public String service(Context context) {
        this.activity = (MainActivity) context;
        while (true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                Log.e("======", "服务器：New connection accepted " +
                        socket.getInetAddress() + ":" + socket.getPort());
//                    char read = (char) System.in.read();
                InputStream inputStream = socket.getInputStream();
                DataInputStream input = new DataInputStream(inputStream);
                byte buffer[] = new byte[1024 * 4];
                int temp = 0;
                // 从InputStream当中读取客户端所发送的数据
                while ((temp = inputStream.read(buffer)) != -1) {
                    x = new String(buffer, 0, temp, "UTF-8");
                    Log.e("======", "service: " + x);
                    activity.readSuccess(x);

                    return x;
                }
//                input.close();
//                out.close();

            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getCause());
            } finally {
//                if (socket != null) {
//                    try {
//                        socket.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
            }
        }


    }

}
